package com.whfc.openapi.api.hdc.service;

import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.util.RandomUtil;
import com.whfc.hdc.dto.AlgDeviceConfigDetailDTO;
import com.whfc.hdc.params.AlgDeviceDataLogParam;
import com.whfc.hdc.service.AlgDeviceConfigService;
import com.whfc.hdc.service.AlgDeviceDataService;
import com.whfc.hdc.service.AlgDeviceStreamService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021-07-20 09:59
 */
@Service
public class HdcAlgOpenServiceImpl implements HdcAlgOpenService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = AlgDeviceDataService.class, version = "1.0.0")
    private AlgDeviceDataService algDeviceDataService;

    @DubboReference(interfaceClass = AlgDeviceConfigService.class, version = "1.0.0")
    private AlgDeviceConfigService algDeviceConfigService;

    @DubboReference(interfaceClass = AlgDeviceStreamService.class, version = "1.0.0")
    private AlgDeviceStreamService algDeviceStreamService;

    @Autowired
    private FilePathConfig filePathConfig;

    @Autowired
    private FileHandler fileHandler;

    @Override
    public void init(String sn) {
        algDeviceDataService.init(sn);
    }

    @Override
    public void uploadResult(String sn, Integer type, Date time, MultipartFile file) {
        //保存文件
        String filename = file.getOriginalFilename();
        String suffix = "";
        if (StringUtils.isNotBlank(filename)) {
            suffix = filename.substring(filename.lastIndexOf("."));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String timeStr = sdf.format(time);
        String filePath = filePathConfig.getFilePath("hdc/alg/file/" + sn + "/" + timeStr);
        String fileName = RandomUtil.getRandomFileName() + suffix;
        String fileUrl = "";
        try {
            //文件上传
            InputStream inputStream = file.getInputStream();
            fileUrl = fileHandler.upload(filePath + "/" + fileName, inputStream);
        } catch (Exception e) {
            logger.warn("算法盒子上传文件失败", e);
        }
        //保存历史数据
        AlgDeviceDataLogParam param = new AlgDeviceDataLogParam();
        param.setSn(sn);
        param.setType(type);
        param.setTime(time);
        param.setImgUrl(fileUrl);
        algDeviceDataService.saveDataLog(param);
    }

    @Override
    public AlgDeviceConfigDetailDTO getConfig(String sn) {
        return algDeviceStreamService.getDeviceStreamConfigDetail(sn);
    }
}
